import cornerstone from 'cornerstone-core';
import cornerstoneTools from 'cs-cornerstone-tools';

export default function isSameOrientation(srcEle, targetEle) {
  if (!srcEle || !targetEle) return false;
  if (srcEle === targetEle) return true;

  let srcImageId, targetImageId, toolData, index;
  toolData = cornerstoneTools.getToolState(srcEle, 'stack');
  if (toolData && toolData && toolData.data && toolData.data.length) {
    index = toolData.data[0].currentImageIdIndex;
    srcImageId = toolData.data[0].imageIds[index];
  }
  toolData = cornerstoneTools.getToolState(targetEle, 'stack');
  if (toolData && toolData && toolData.data && toolData.data.length) {
    index = toolData.data[0].currentImageIdIndex;
    targetImageId = toolData.data[0].imageIds[index];
  }

  if (!srcImageId || !targetImageId) return false;

  const { getOrientationString } = cornerstoneTools.orientation;
  const { rowCosines: srcRowCosines, columnCosines: srcColumnCosines } =
    cornerstone.metaData.get('imagePlaneModule', srcImageId) || {};
  const { rowCosines: targetRowCosines, columnCosines: targetColumnCosines } =
    cornerstone.metaData.get('imagePlaneModule', targetImageId) || {};

  if (
    !srcRowCosines ||
    !srcColumnCosines ||
    !targetRowCosines ||
    !targetColumnCosines
  )
    return false;

  const srcRowStr = getOrientationString(srcRowCosines);
  const srcColumnStr = getOrientationString(srcColumnCosines);
  const targetRowStr = getOrientationString(targetRowCosines);
  const targetColumnStr = getOrientationString(targetColumnCosines);

  return srcRowStr === targetRowStr && srcColumnStr === targetColumnStr;
}
